package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    ServerSocket serverSocket;  //服务器端套接字，监听客户端请求，得到客户端的套接口，使用套接口传送数据
    public Server(int port){
        try {
            serverSocket=new ServerSocket(port);   //根据端口号创建了服务器的套接字
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void startService(){
        while (true){
            try {
                Socket socket=serverSocket.accept();  //接受到客户端的请求连接
                if(socket!=null)
                {
                    System.out.print(socket.getInetAddress()+":");
                    receiveMessage(socket);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //接收信息
    public void receiveMessage(Socket s){
        try {
            //BufferedReader高端字符读入流，InputStreamReader是低端字符读入流，数据源是网络套接口，来自于远程电脑
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(s.getInputStream()));
            //在服务器的控制台上打印读入流的信息
            System.out.println(bufferedReader.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void  main(String args[]){
       // new Server(8888).startService();
        Server server=new Server(8888);  //创建一个服务器，端口号是8888
        server.startService();                //启动服务
    }
}
